import path from "path";
import http from "http";

// 配置环境变量
import dotenv from "dotenv";
dotenv.config();
import express from "express";
import session from "express-session";

// 捕获异步错误
import "express-async-errors";

// 创建路由
import { createRouter } from "./routes/index";
import { createSocket } from "./routes/socket";
import { formatDate } from "./utils/tools";
import { ClientInfo } from "./utils/ClientInfo";
const app = express();

const flowRecord: any = {
  count: 0,
  prevDate: null,
};

app.use(express.json());

app.get("/api/getGroupName", async (req: any, res: any) => {
  const ipAdd = await ClientInfo.getClientInfo(req, "0", "0");
  const parts = ipAdd.location.split("市")[0];

  let result = "";
  if (parts.includes("省")) {
    result = parts.split("省")[1];
  } else {
    result = parts.slice(2);
  }

  res.send(result);
});

app.get("/api/payCount", (_req: any, res: any) => {
  flowRecord.count += 1;
  flowRecord.prevDate = formatDate(new Date());
  res.send(null);
});

app.get("/api/getPayRecord", (_req: any, res) => {
  res.send(flowRecord);
});

app.use(
  "/",
  (_req, _res, next: any) => {
    next();
  },
  express.static(path.join(__dirname, "../public"))
);

app.use(
  session({
    secret: "wieujflskjdfhokk",
  })
);
createRouter(app);

/**
 * 使用socket
 */
const httpServer = http.createServer(app);
createSocket(httpServer);

// 启动服务
httpServer.listen(process.env.Y_APP_PORT, () => {
  console.log(`监听${process.env.Y_APP_PORT}端口中...`);
});
